package cz.martindobias.aladin;

import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

public abstract class AbstractResourceHandler implements ResourceHandler {
    private Activity activity;
    private Uri uri;

    protected AbstractResourceHandler(Activity activity, Uri uri) {
        this.activity = activity;
        this.uri = uri;
    }

    public void init() {
        Cursor cursor = this.activity.managedQuery(this.uri, null, null, null, null);
        if(cursor != null) {
            if(!cursor.isAfterLast()) {
                this.update(cursor);
            }
            cursor.registerContentObserver(new ContentObserver(new Handler()) {
                @Override
                public boolean deliverSelfNotifications() {
                    return false;
                }

                @Override
                public void onChange(boolean selfChange) {
                    update();
                }
            });
        } else {
            this.update(null);
        }
    }

    public void update() {
        Cursor cursor = this.activity.getContentResolver().query(this.uri, null, null, null, null);
        this.update(cursor);
        if(cursor != null) {
            cursor.close();
        }
    }

    protected abstract void update(Cursor cursor);

}
